/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.config.typehandler;

import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.openislands.oi.constant.RoleType;
import org.openislands.oi.pojo.dto.OperatorDTO;
import org.openislands.oi.util.ObjectUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonTypeHandler<T> implements TypeHandler<T> {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, T object, JdbcType jdbcType) throws SQLException {
        if (object == null) {
            Type genericType = getGenericType();
            preparedStatement.setString(i, genericType instanceof ParameterizedType &&
                    Collection.class.isAssignableFrom(((Class<?>)((ParameterizedType) genericType).getRawType())) ? "[]" : "{}");
            return;
        }
        preparedStatement.setString(i, ObjectUtils.object2Json(object));
    }

    @Override
    public T getResult(ResultSet resultSet, String s) throws SQLException {
        final String value = resultSet.getString(s);
        return value == null ? defaultResult() : ObjectUtils.json2Object(value, new TypeReferenceImpl<>(getGenericType()));
    }

    @Override
    public T getResult(ResultSet resultSet, int i) throws SQLException {
        final String value = resultSet.getString(i);
        return value == null ? defaultResult() : ObjectUtils.json2Object(value, new TypeReferenceImpl<>(getGenericType()));
    }

    @Override
    public T getResult(CallableStatement callableStatement, int i) throws SQLException {
        final String value = callableStatement.getString(i);
        return value == null ? defaultResult() : ObjectUtils.json2Object(value, new TypeReferenceImpl<>(getGenericType()));
    }

    public Type getGenericType() {
        final Type genericSuperclass = this.getClass().getGenericSuperclass();
        final Type[] actualTypeArguments = ((ParameterizedType) genericSuperclass).getActualTypeArguments();
        return actualTypeArguments[0];
    }

    public T defaultResult() {
        return null;
    }

    public static class TypeReferenceImpl<T> extends TypeReference<T> {
        private final Type genericType;

        public TypeReferenceImpl(Type genericType) {
            this.genericType = genericType;
        }

        @Override
        public Type getType() {
            return genericType;
        }
    }

    public static class StringMap extends JsonTypeHandler<Map<String, Object>> {
        @Override
        public Map<String, Object> defaultResult() {
            return new HashMap<>();
        }
    }

    public static class FederatedNodes extends JsonTypeHandler<Map<RoleType, List<String>>> {
        @Override
        public Map<RoleType, List<String>> defaultResult() {
            return new HashMap<>();
        }
    }

    public static class Operator extends JsonTypeHandler<OperatorDTO> {
    }
}
